﻿/*
    This software is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

    Copyright (C) 2010 Daniel Deptford (redmercury@gmail.com)
 
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in
        all copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace COLLADASharp
{
    using COLLADA = COLLADASharp.Core.COLLADA;

    public static class Loader
    {
        private static ElementNode COLLADAElement;

        public static COLLADA Load(string filename)
        {
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                XmlReader reader = XmlReader.Create(fs);
                return Load(reader);
            }
        }
                
        public static COLLADA Load(XmlReader reader)
        {
            if (COLLADAElement == null)
            {
                COLLADAElement = new ElementNode(typeof(COLLADA));
            }

            return (COLLADA)COLLADAElement.Load(reader);
        }

        private abstract class FieldBase
        {
            internal string Name { get; set; }
            internal NodeProperty NodeProperty { get; set; }

            protected FieldBase(string name, NodeProperty nodeProperty)
            {
                Name = name;
                NodeProperty = nodeProperty;
            }

            abstract public void Load(XmlReader reader, DAENode owner);
        }

        internal delegate object BuiltinConverter(string value);

        internal static BuiltinConverter GetConverter(Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.Boolean:
                    return new BuiltinConverter((x) => {return Boolean.Parse(x);});
                case TypeCode.Byte:
                    return new BuiltinConverter((x) => {return Byte.Parse(x);});
                case TypeCode.Char:
                    return new BuiltinConverter((x) => { return Boolean.Parse(x); });
                case TypeCode.DateTime:
                    return new BuiltinConverter((x) => { return DateTime.Parse(x); });
                case TypeCode.Decimal:
                    return new BuiltinConverter((x) => { return Decimal.Parse(x); });
                case TypeCode.Double:
                    return new BuiltinConverter((x) => { return Double.Parse(x); });
                case TypeCode.Int16:
                    return new BuiltinConverter((x) => { return Int16.Parse(x); });
                case TypeCode.Int32:
                    return new BuiltinConverter((x) => { return Int32.Parse(x); });
                case TypeCode.Int64:
                    return new BuiltinConverter((x) => { return Int64.Parse(x); });
                case TypeCode.SByte:
                    return new BuiltinConverter((x) => { return SByte.Parse(x); });
                case TypeCode.Single:
                    return new BuiltinConverter((x) => { return Single.Parse(x); });
                case TypeCode.String:
                    return new BuiltinConverter((x) => { return x; });
                case TypeCode.UInt16:
                    return new BuiltinConverter((x) => { return UInt16.Parse(x); });
                case TypeCode.UInt32:
                    return new BuiltinConverter((x) => { return UInt32.Parse(x); });
                case TypeCode.UInt64:
                    return new BuiltinConverter((x) => { return UInt64.Parse(x); });
                default:
                    Debug.Assert(false);
                    break;
            }
            return null;
        }

        internal static bool IsGenericIList(Type type, out Type elementType)
        {
            for (Type t = type; t != null; t = t.BaseType)
            {
                foreach (Type interfaceType in t.GetInterfaces())
                {
                    if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
                    {
                        elementType = interfaceType.GetGenericArguments()[0];
                        return true;
                    }
                }
            }
            elementType = type;
            return false;
        }

        private class AttributeField : FieldBase
        {
            public AttributeField(string name, NodeProperty nodeProperty)
                : base(name, nodeProperty)
            {
            }

            public override void Load(XmlReader reader, DAENode owner)
            {
                object value = Convert.ChangeType(reader.Value, NodeProperty.PropertyType);
                owner.SetValue(NodeProperty, value);
            }
        }

        private class ElementField : FieldBase
        {
            internal int Order { get; set; }
            internal bool IsList { get; set; }
            internal ElementBase Element { get; set; }

            public ElementField(string name, NodeProperty nodeProperty, int order, bool isList, ElementBase element)
                : base(name, nodeProperty)
            {
                Order = order;
                IsList = isList;
                Element = element;
            }

            public override void Load(XmlReader reader, DAENode owner)
            {
                object fieldObject = Element.Load(reader);

                if (IsList)
                {
                    IList fieldList = (IList)owner.GetValue(NodeProperty);
                    if (fieldList == null)
                    {
                        fieldList = (IList)Activator.CreateInstance(NodeProperty.PropertyType);
                        owner.SetValue(NodeProperty, fieldList);
                    }
                    fieldList.Add(fieldObject);
                }
                else
                {
                    owner.SetValue(NodeProperty, fieldObject);
                }
            }
        }

        private abstract class ElementBase
        {
            protected ElementBase()
            {
            
            }

            public abstract object Load(XmlReader reader);
        }

        private class ElementEnum : ElementBase
        {
            private Type enumType;
            public ElementEnum(Type enumType)
            {
                Debug.Assert(enumType.IsEnum);
                this.enumType = enumType;
            }

            public override object Load(XmlReader reader)
            {
                string value = reader.ReadElementString();
                return Enum.Parse(enumType, value);
            }
        }

        private class ElementBuiltin  : ElementBase
        {
            private BuiltinConverter converter;
            public ElementBuiltin(Type builtinType)
            {
                converter = GetConverter(builtinType);
            }

            public override object Load(XmlReader reader)
            {
                string value = reader.ReadElementString();
                return converter(value);
            }
        }

        private class ElementBuiltinCollection : ElementBase
        {
            private BuiltinConverter converter;
            private Type collectionType;
            private Type elementType;

            public ElementBuiltinCollection(Type collectionType, Type elementType)
            {
                this.collectionType = collectionType;
                this.elementType = elementType;
                converter = GetConverter(elementType);
            }

            public override object Load(XmlReader reader)
            {
                IList collection = (IList)Activator.CreateInstance(collectionType);
                string value = reader.ReadElementString();
                string [] values = value.Split(new char[]{' ','\n'}, StringSplitOptions.RemoveEmptyEntries);
                foreach (var stringValue in values)
                {
                    collection.Add(converter(stringValue));
                }

                return collection;
            }
        }

        private class ElementNode : ElementBase
        {
            private Type elementType;
            private Dictionary<string, ElementField> elementFields = new Dictionary<string, ElementField>();
            private Dictionary<string, AttributeField> attributeFields = new Dictionary<string, AttributeField>();

            private static Dictionary<Type, ElementBase> elements = new Dictionary<Type, ElementBase>();

            public ElementNode(Type elementType)
            {
                this.elementType = elementType;
                FieldInfo[] fields = elementType.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
                foreach (var field in fields)
                {
                    if(field.FieldType != typeof(NodeProperty))
                        continue;

                    NodeProperty property = (NodeProperty)field.GetValue(null);

                    Type propertyType = property.PropertyType;
                    bool isList = IsGenericIList(propertyType, out propertyType);
                    bool isDAENode = typeof(DAENode).IsAssignableFrom(propertyType);

                    var elementAttributeObjects = field.GetCustomAttributes(typeof(DAEElementAttribute), false);
                    if(elementAttributeObjects.Length != 0)
                    {
                        foreach(var elementAttribute in elementAttributeObjects.Cast<DAEElementAttribute>())
                        {
                            if (propertyType.IsAssignableFrom(elementAttribute.ElementType))
                            {
                                ElementBase fieldElement = null;
                                if (!elements.TryGetValue(elementAttribute.ElementType, out fieldElement))
                                {
                                    if (isDAENode)
                                    {
                                        fieldElement = new ElementNode(elementAttribute.ElementType);
                                    }
                                    else
                                    {
                                        if (isList)
                                        {
                                            fieldElement = new ElementBuiltinCollection(property.PropertyType, propertyType);
                                        }
                                        else
                                        {
                                            if (propertyType.IsEnum)
                                                fieldElement = new ElementEnum(propertyType);
                                            else
                                                fieldElement = new ElementBuiltin(propertyType);
                                        }
                                    }
                                    elements.Add(elementAttribute.ElementType, fieldElement);
                                }

                                ElementField elementField = new ElementField(elementAttribute.XmlName, property, elementAttribute.Order, isList && isDAENode, fieldElement);
                                elementFields.Add(elementAttribute.XmlName, elementField);
                            }
                        }
                    }

                    var attributeAttributeObject = field.GetCustomAttributes(typeof(DAEAttributeAttribute), false).Cast<DAEAttributeAttribute>().FirstOrDefault();
                    if (attributeAttributeObject != null)
                    {
                        AttributeField attributeField = new AttributeField(attributeAttributeObject.XmlName, property);
                        attributeFields.Add(attributeAttributeObject.XmlName, attributeField);
                    }
                }
            }

            public override object Load(XmlReader reader)
            {
                DAENode readingObject = (DAENode)Activator.CreateInstance(elementType);

                for (int attributeIndex = 0; attributeIndex < reader.AttributeCount; attributeIndex++)
                {
                    reader.MoveToAttribute(attributeIndex);
                    AttributeField field = null;
                    if(attributeFields.TryGetValue(reader.Name, out field))
                    {
                        field.Load(reader, readingObject);
                    }
                }

                reader.MoveToContent();
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return readingObject;
                }
                reader.ReadStartElement();

                int currentOrder = 0;
                while (reader.NodeType != XmlNodeType.EndElement)
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        bool wasRead = false;
                        ElementField field = null;
                        if (elementFields.TryGetValue(reader.Name, out field))
                        {
                            if (field.Order >= currentOrder)
                            {
                                currentOrder = field.Order;
                                field.Load(reader, readingObject);
                                reader.MoveToContent();
                                wasRead = true;
                            }
                        }
                        if (!wasRead)
                        {
                            reader.Skip();
                        }
                    }
                    else
                    {
                        reader.Read();
                    }
                }

                reader.ReadEndElement();
                return readingObject;
            }
        }
    }
}
